{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {
    "editable": true,
    "raw_mimetype": "text/restructuredtext",
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    ".. _nb_matrix_inversion:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Matrix Inversion\n",
    "\n",
    "In this case study, the optimization of a matrix shall be illustrated. Of course, we all know that there are very efficient algorithms for calculating an inverse of a matrix. However, for the sake of illustration, a small example shall show that pymoo can also be used to optimize matrices or even tensors.\n",
    "\n",
    "Assuming matrix `A` has a size of `n x n`, the problem can be defined by optimizing a vector consisting of `n**2` variables. During evaluation the vector `x`, is reshaped to inversion of the matrix to be found (and also stored as the attribute `A_inv` to be retrieved later)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from pymoo.core.problem import ElementwiseProblem\n",
    "\n",
    "\n",
    "class MatrixInversionProblem(ElementwiseProblem):\n",
    "\n",
    "    def __init__(self, A, **kwargs):\n",
    "        self.A = A\n",
    "        self.n = len(A)\n",
    "        super().__init__(n_var=self.n**2, n_obj=1, xl=-100.0, xu=+100.0, **kwargs)\n",
    "\n",
    "\n",
    "    def _evaluate(self, x, out, *args, **kwargs):\n",
    "        A_inv = x.reshape((self.n, self.n))\n",
    "        out[\"A_inv\"] = A_inv\n",
    "\n",
    "        I = np.eye(self.n)\n",
    "        out[\"F\"] = ((I - (A @ A_inv)) ** 2).sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "Now let us see what solution is found to be optimal"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from pymoo.algorithms.soo.nonconvex.de import DE\n",
    "from pymoo.optimize import minimize\n",
    "\n",
    "np.random.seed(1)\n",
    "A = np.random.random((2, 2))\n",
    "\n",
    "problem = MatrixInversionProblem(A)\n",
    "\n",
    "algorithm = DE()\n",
    "\n",
    "res = minimize(problem,\n",
    "               algorithm,\n",
    "               seed=1,\n",
    "               verbose=False)\n",
    "\n",
    "opt = res.opt[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "In this case the true optimum is actually known. It is"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 2.39952297e+00, -5.71699951e+00],\n",
       "       [-9.07758630e-04,  3.30977861e+00]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.linalg.inv(A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "Let us see if the black-box optimization algorithm has found something similar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 2.39916052e+00, -5.71656622e+00],\n",
       "       [-8.41267527e-04,  3.30978797e+00]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "opt.get(\"A_inv\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "This small example shall have illustrated how a matrix can be optimized. In fact, this is implemented by optimizing a vector of variables that are reshaped during evaluation."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
